//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "eic.h"
#include "MTAG_Outils.h"
#include "CIBExtract.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------
#define MODULE_TAG MTAG_CIBEXTRACT
//---------------------------------------------------------------------------
// ValidCtrCheck est utilisé est utilisé pour être sûr que les composants créés n'ont
// aucune fonction virtuelle pure.
//

static inline void ValidCtrCheck(CIBExtract *)
{
    new CIBExtract(NULL);
}
//---------------------------------------------------------------------------
__fastcall CIBExtract::CIBExtract(TComponent* Owner) : inherited( Owner)
{
}
//---------------------------------------------------------------------------
TIBSQL * __fastcall CIBExtract::Create_IBSQL(void)
{
  TIBSQL *qry = NULL;
  try
  {
    qry = new TIBSQL(NULL);
    qry->Database = Database;
    if(Transaction != Database->DefaultTransaction)
      qry->Transaction = Transaction;
  }
  catch(Exception &e)
  {
    EICDisplayException(TAGL,e);
  }
  return qry;
}
//---------------------------------------------------------------------------
void __fastcall CIBExtract::ExtractValGenerator(const AnsiString &ObjectName)
{
  TIBSQL *qrySelect = NULL;
  bool    DidActivate = false;

  try
  {
    if(ObjectName.IsEmpty()) return;

    if(!Transaction->Active)
    {
      Transaction->StartTransaction();
      DidActivate = true;
    }
    Items->Clear();

    qrySelect = Create_IBSQL();
    qrySelect->SQL->Text = "SELECT GEN_ID("+ObjectName.Trim()+",0) FROM RDB$DATABASE";
    qrySelect->ExecQuery();
    if(qrySelect->RecordCount > 0)
      Items->Add("SET GENERATOR \""+ObjectName.Trim()+"\" to "+qrySelect->Fields[0]->AsString+";");

    if(DidActivate)
      Transaction->Commit();
  }
  catch(Exception &e)
  {
    EICDisplayException(TAGL,e);
  }
  if(qrySelect) delete qrySelect;
}
//---------------------------------------------------------------------------
void __fastcall CIBExtract::ExtractTrigger(const AnsiString &ObjectName, bool _bSetTerm)
{
  TExtractTypes ExtractTypes;

  try
  {
    ExtractObject(eoTrigger,ObjectName,ExtractTypes);
    for(int i = 0; i < Items->Count; i++)
    {
      if(!_bSetTerm && (Items->Strings[i]).AnsiPos("^"))
      {
        Items->Delete(i);
        i--;
      }
    }
  }
  catch(Exception &e)
  {
    EICDisplayException(TAGL,e);
  }
}
//---------------------------------------------------------------------------
void __fastcall CIBExtract::ExtractData(const AnsiString &ObjectName)
{
  TIBSQL     *qrySelect = NULL;
  AnsiString  Fields, Line, Values;
  bool        DidActivate = false;

  try
  {
    if(!Transaction->Active)
    {
      Transaction->StartTransaction();
      DidActivate = true;
    }
    Items->Clear();

    qrySelect = Create_IBSQL();
    qrySelect->SQL->Add("SELECT * FROM "+ObjectName.Trim());
    qrySelect->ExecQuery();
    for(int i = 0; i < (qrySelect->Current())->Count; i++) {
        if(!Fields.IsEmpty())
            Fields += ", ";
        Fields += qrySelect->Fields[i]->AsXSQLVAR->sqlname;
    }
    
    while(!qrySelect->Eof)
    {
      Line = "INSERT INTO "+ObjectName.Trim()+" ("+Fields+") VALUES (";
      Values = EmptyStr;
      for(int i = 0; i < (qrySelect->Current())->Count; i++)
      {
        if(!Values.IsEmpty())
          Values += ", ";
        if(qrySelect->Fields[i]->IsNull && (qrySelect->Fields[i]->SQLType != SQL_ARRAY) && (qrySelect->Fields[i]->SQLType != SQL_BLOB))
          Values += "NULL";
        else
        {
          switch(qrySelect->Fields[i]->SQLType)
          {
            case SQL_TEXT :
            case SQL_VARYING :
              Values += QuotedStr((qrySelect->Fields[i]->AsString).Trim()); break;
            case SQL_TYPE_DATE :
              Values += QuotedStr((qrySelect->Fields[i]->AsDateTime).FormatString("yyyy-mm-dd")); break;
            case SQL_TYPE_TIME :
              Values += QuotedStr((qrySelect->Fields[i]->AsDateTime).FormatString("hh:nn:ss")); break;
            case SQL_TIMESTAMP :
              Values += QuotedStr((qrySelect->Fields[i]->AsDateTime).FormatString("yyyy-mm-dd hh:nn:ss")); break;
            case SQL_SHORT :
            case SQL_LONG :
            case SQL_INT64 :
            case SQL_DOUBLE :
            case SQL_FLOAT :
            case SQL_D_FLOAT :
              {
                AnsiString ValTemp = (qrySelect->Fields[i]->AsString).Trim();
                int pos = ValTemp.LastDelimiter(",");
                if(pos)
                {
                  ValTemp = ValTemp.SubString(1,pos-1)+"."+ValTemp.SubString(pos+1,ValTemp.Length());
                }
                Values += QuotedStr(ValTemp);
              }
              break;
            default : Values += QuotedStr((qrySelect->Fields[i]->AsString).Trim()); break;
          }
        }
      }
      Items->Add(Line+Values+");");
      qrySelect->Next();
    }

    if(DidActivate)
      Transaction->Commit();
  }
  catch(Exception &e)
  {
    EICDisplayException(TAGL,e);
  }
  if(qrySelect) delete qrySelect;
}

//---------------------------------------------------------------------------
void __fastcall CIBExtract::ExtractValDescription(const AnsiString &ObjectName)
{
  TIBSQL *qrySelect = NULL;
  bool    DidActivate = false;

  try
  {
    if(ObjectName.IsEmpty()) return;

    if(!Transaction->Active)
    {
      Transaction->StartTransaction();
      DidActivate = true;
    }
    Items->Clear();

    qrySelect = Create_IBSQL();
    qrySelect->SQL->Text = "SELECT RDB$DESCRIPTION FROM RDB$RELATIONS WHERE RDB$RELATION_NAME='"+ObjectName.Trim()+"'";
    qrySelect->ExecQuery();
    if(qrySelect->RecordCount > 0)
      Items->Add(   "UPDATE RDB$RELATIONS SET RDB$DESCRIPTION = "
                    + QuotedStr(qrySelect->Fields[0]->AsString)
                    + " WHERE RDB$RELATION_NAME='"+ObjectName.Trim()+"';");

    if(DidActivate)
      Transaction->Commit();
  }
  catch(Exception &e)
  {
    EICDisplayException(TAGL,e);
  }
  if(qrySelect) delete qrySelect;
}
//---------------------------------------------------------------------------
namespace Cibextract
{
    void __fastcall PACKAGE Register()
    {
         TComponentClass classes[1] = {__classid(CIBExtract)};
         RegisterComponents("EIC Outils", classes, 0);
    }
}
//---------------------------------------------------------------------------
